package com.dashu.core.config;


import com.alibaba.fastjson.JSON;
import com.dashu.base.bean.Tokenbean;
import com.dashu.base.enums.ReplRyCode;
import com.dashu.base.utils.ToEntityAnStr;
import com.dashu.core.result.ResultBean;
import com.dashu.base.utils.http.token.TokenTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Slf4j
public class TokenConfig {
    public static void tokenCors(String data, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if (!StringUtils.isEmpty(data)) {
            Tokenbean tokenbean = ToEntityAnStr.string2Obj(data, Tokenbean.class);
            if (!tokenbean.getType().equals("login") && !tokenbean.getType().equals("defult")) {
                boolean isToken = TokenTools.judgeTokenIsEqual(req, "Authorization", tokenbean.getUserKey());
                if (!isToken) {
                    ResultBean<Object> resultData = new ResultBean<>(ReplRyCode.HEDERS_TOKEN.getCode(),ReplRyCode.HEDERS_TOKEN.getMessage(), isToken);
                    String reData = String.valueOf(JSON.toJSON(resultData));
                    returnData(resp, reData);
                }
            }
        }
    }

    public static void returnData(HttpServletResponse resp, String reData) throws IOException {
        {
            PrintWriter writer = null;
            OutputStreamWriter osw = null;
            try {
                osw = new OutputStreamWriter(resp.getOutputStream(),
                        "UTF-8");
                writer = new PrintWriter(osw, true);
                String jsonStr = reData;
                writer.write(jsonStr);
                writer.flush();
                writer.close();
                osw.close();
            } catch (UnsupportedEncodingException e) {
                log.error("过滤器返回信息失败:" + e.getMessage(), e);
            } catch (IOException e) {
                log.error("过滤器返回信息失败:" + e.getMessage(), e);
            } finally {
                if (null != writer) {
                    writer.close();
                }
                if (null != osw) {
                    osw.close();
                }
            }
            return;
        }
    }
}

